import numpy as np
import os

def pre_process(filename,t_Hz1,t_1s):
    # read data
    samples_n = t_Hz1*t_1s*2
    # print(samples_n)
    numData2 = np.genfromtxt(filename,skip_header=1,delimiter=",",max_rows=samples_n)

    # seprate gyro data and acc data
    gyro_data = []
    acc_data = []

    for i in range(numData2.shape[0]):
        if numData2[i,1] == 1:
            acc_data.append(numData2[i,2:])
        else:
            gyro_data.append(numData2[i, 2:])

    acc_data = np.array(acc_data)
    gyro_data = np.array(gyro_data)

    # process time stamp
    start_time = numData2[0,2]
    acc_data[:,0] = (acc_data[:,0] - start_time) * 1e-5
    gyro_data[:,0] = (gyro_data[:,0] - start_time) * 1e-5

    acc_data = acc_data[1:,:]
    gyro_data = gyro_data[1:,:]

    acc_data = np.c_[acc_data[:,0:4],acc_data[:,7]]
    gyro_data = np.c_[gyro_data[:,0:1],gyro_data[:,4:8]]

    # print(acc_data.shape)
    # print(gyro_data.shape)

    return acc_data,gyro_data

def temperature_fitting(accd,gyrod,smoothn):
    smoothni = int(smoothn)

    # process acc data
    length = int(accd.shape[0] / smoothn)
    smooth_data = []

    for i in range(length-1):
        smooth_data.append((accd[smoothni*i:smoothni*i+smoothni, :]).mean(axis=0))
    smooth_data = np.array(smooth_data)

    acc_cof = []
    for i in range(3):
        acc_cof_temp = np.polyfit(smooth_data[:,4], smooth_data[:,i+1], 1)
        acc_cof.append(acc_cof_temp)
    acc_cof = np.array(acc_cof)

    # acc to compensta average to 0
    accx_a = smooth_data[:,1].mean()
    accy_a = smooth_data[:,2].mean()
    accz_a = smooth_data[:,3].mean()

    acc_cof[0,1] = acc_cof[0,1] - accx_a
    acc_cof[1,1] = acc_cof[1,1] - accy_a
    acc_cof[2,1] = acc_cof[2,1] - accz_a

    # process gyro data
    length = int(gyrod.shape[0] / smoothn)
    smooth_data = []

    for i in range(length-1):
        smooth_data.append((gyrod[smoothni*i:smoothni*i+smoothni, :]).mean(axis=0))
    smooth_data = np.array(smooth_data)

    gyro_cof = []
    for i in range(3):
        gyro_cof_temp = np.polyfit(smooth_data[:,4], smooth_data[:,i+1], 1)
        gyro_cof.append(gyro_cof_temp)
    gyro_cof = np.array(gyro_cof)

    return acc_cof,gyro_cof

def find_file(dirs):
    dir_ab = os.path.abspath(dirs)

    lists = os.listdir(dir_ab)

    for i in range(len(lists)):
        # paths = os.path.join(dir_ab, lists[i])
        paths = lists[i]
        if os.path.isfile(paths):
            lists[i] = paths

    return dir_ab,lists

def data_smooth(data, smooth_size):

    length = int(data.shape[0] / smooth_size)
    smooth_data = np.zeros([length, data.shape[1]])

    for i in range(length):
        smooth_data[i] = data[smooth_size * i:smooth_size * i + smooth_size, :].mean(axis=0)

    return smooth_data

